package com.codedancer.campus.manager.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codedancer.campus.manager.service.IChatMessageService;
import com.codedancer.campus.manager.service.bo.chatMessage.ChatMessagePageSearchBo;
import com.codedancer.campus.manager.service.vo.chatMessage.ChatMessageVo;
import com.codedancer.campus.mapper.ChatMessageMapper;
import com.codedancer.campus.po.ChatMessage;
import com.codedancer.campus.qo.chatMessage.ChatMessageSearchQo;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class ChatMessageServiceImpl implements IChatMessageService {

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    /**
     * 分页查询历史聊天记录
     *
     * @param chatMessagePageSearchBo
     * @return
     */
    @Override
    public IPage<ChatMessageVo> pageHistory(ChatMessagePageSearchBo chatMessagePageSearchBo) {
        ChatMessageSearchQo chatMessageSearchQo = BeanUtil.copyProperties(chatMessagePageSearchBo,
            ChatMessageSearchQo.class);
        IPage<ChatMessage> chatMessageIPage = chatMessageMapper.pageHistory(
            new Page<ChatMessage>(chatMessagePageSearchBo.getPage(),
                chatMessagePageSearchBo.getSize()), chatMessageSearchQo);
        IPage<ChatMessageVo> chatMessageVoIPage = new Page<>();
        List<ChatMessageVo> chatMessageVos;
        chatMessageVos = chatMessageIPage.getRecords().stream().map(chatMessage -> {
            ChatMessageVo chatMessageVo = BeanUtil.copyProperties(chatMessage, ChatMessageVo.class);
            chatMessageVo.setSendUserUuid(chatMessage.getSendUser().getUuid());
            chatMessageVo.setSendUserName(chatMessage.getSendUser().getNickName());
            chatMessageVo.setSendUserAvatar(chatMessage.getSendUser().getAvatar());
            chatMessageVo.setReceiveUserUuid(chatMessage.getReceiveUser().getUuid());
            chatMessageVo.setReceiveUserName(chatMessage.getReceiveUser().getNickName());
            chatMessageVo.setReceiveUserAvatar(chatMessage.getReceiveUser().getAvatar());
            return chatMessageVo;
        }).collect(Collectors.toList());
        chatMessageVoIPage.setTotal(chatMessageIPage.getTotal());
        chatMessageVoIPage.setRecords(chatMessageVos);
        return chatMessageVoIPage;
    }
}
